#include <QTextStream>
#include <QFile>
#include <QStringList>
#include <iostream>
#include <QSqlQuery>

#include "data.h"

Data::Data()
{	
	for (int i=0;i<TIME;i++){
		if (i<5) timeList << QString("%1 AM").arg(i+8);
		else timeList << QString("%1 PM").arg(i-4);
	}
//	initialData();
	readFile();
//	writeFile();
	writeTables();
}

void Data::initialData()
{
	subjectList << "Data Structure" << "Math" << "Logic Design" << "Information System" << "Economy";
	
	placeList << "Lab 1" << "Lab 2" << "Lab 3" << "Lab 4";
	placeList << "Mod 2" << "Mod 5" << "Mod 7" << "Mod 14" << "Mod 15" << "Mod 18";
	
	teacherList << "Eng. Reham" << "Eng. Nagwa" << "Eng. Mervat" << "Eng. Shahenda";
	teacherList << "Eng. Sameer" << "Eng. Siam" << "Eng. Haggag" << "Eng. Islam";
	teacherList << "Dr. Shereef Brakat" << "Dr. Ahmed Atwan" << "Dr. Alaa" << "Dr. Magdy";
}

void Data::readFile()
{
	QFile file("data.txt");
	if (!file.open(QIODevice::ReadOnly)) {
		std::cerr << "Cannot open file for writing"
			<< qPrintable(file.errorString()) << std::endl;
		return ;
	}
	
	QTextStream in(&file);
	QString line;
	QStringList *list=0;
	do{
		line = in.readLine();
		if( line.isEmpty() ) continue;

		if ( line == "Subjects:" ) { list = &subjectList; continue;}
		if ( line == "Places:" )   { list = &placeList;   continue;}
		if ( line == "Teachers:" ) { list = &teacherList; continue;}
		
		*list << line;
	}while(!in.atEnd());
}

void Data::writeFile()
{
	QFile file("data.txt");
	if (!file.open(QIODevice::WriteOnly)) {
		std::cerr << "Cannot open file for writing"
			<< qPrintable(file.errorString()) << std::endl;
		return ;
	}
	
	QTextStream out(&file);
	out << "Subjects:\n";
	for (int i=0;i<subjectList.size();i++) out << subjectList.at(i) << "\n";
		
	out << "\nPlaces:\n";
	for (int i=0;i<placeList.size();i++) out << placeList.at(i) << "\n";
		
	out << "\nTeachers:\n";
	for (int i=0;i<teacherList.size();i++) out << teacherList.at(i) << "\n";
}

void Data::writeTables()
{
	QSqlQuery query;

    for (int i=0;i<subjectList.size();i++){
    	query.exec( QString("insert into subjects values( %1,'%2')").arg(i).arg(subjectList.at(i)) );
   	}
   	
    for (int i=0;i<placeList.size();i++){
    	query.exec( QString("insert into places values( %1,'%2')").arg(i).arg(placeList.at(i)) );
   	}
   	
    for (int i=0;i<teacherList.size();i++){
    	query.exec( QString("insert into teachers values( %1,'%2')").arg(i).arg(teacherList.at(i)) );
   	}
   	
    for (int i=0;i<timeList.size();i++){
    	query.exec( QString("insert into times values( %1,'%2')").arg(i).arg(timeList.at(i)) );
   	}
}
